package net.gazhi.delonix.weixin.mp.api;

import net.gazhi.delonix.weixin.mp.MPConfig;
import net.gazhi.delonix.weixin.mp.api.response.GetCallbackIPResponse;
import net.gazhi.delonix.weixin.mp.api.response.GetTokenResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class BaseAPI {

	private static Log log = LogFactory.getLog(BaseAPI.class);

	/**
	 * 刷新 AccessToken
	 * 
	 * @param config
	 * @return
	 */
	public static int refreshAccessToken(MPConfig config) {
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + config.getAppId() + "&secret=" + config.getAppSecret();
		GetTokenResponse response = APIUtils.executeSSLGet(url, GetTokenResponse.class);
		if (response != null) {
			if (response.getErrcode() != 0) {
				log.error(url);
				log.error("Failed to Refresh Access Token: " + response.getErrcode() + " " + response.getErrmsg());
			} else {
				config.setAccessToken(response.getAccessToken());
				return response.getExpiresIn();
			}
		}
		return -1;
	}

	public static void initCabackIPList(MPConfig config) {
		String url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=" + config.getAccessToken();
		GetCallbackIPResponse response = APIUtils.executeSSLGet(url, GetCallbackIPResponse.class);
		if (response != null) {
			if (response.getErrcode() != 0) {
				log.error("Failed to Refresh Access Token: " + response.getErrcode() + " " + response.getErrmsg());
			} else {
				config.getCabackIPList().clear();
				for (String ip : response.getIpList()) {
					config.getCabackIPList().add(ip);
				}
			}
		}
	}

}
